package com.xbn.netty.nettySocket;

import com.xbn.netty.nettyHeartBeat.MyServerHeartHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author XBN
 * @date 2020/10/21 20:03
 * @email 78742541@qq.com
 */

public class MyServer {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup=new NioEventLoopGroup(1);
        EventLoopGroup workerGroup=new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))//在bossGroup中增加一个日志处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //因为基于http协议，所以我们需要http的编解码器
                            pipeline.addLast(new HttpServerCodec());
                            //以块方式写，需要添加一个chunkedWrite处理器
                            pipeline.addLast(new ChunkedWriteHandler());
                            /*
                            * http在传输过程中是分段传输的，HttpObjectAggregator可以将多个分段数据聚合在一起
                            * 这就是为什么我们在发送大量数据的时候会发出多次http请求
                            * */
                            pipeline.addLast(new HttpObjectAggregator(8192));
                             /*
                             * 对于webSocket，它的数据是以帧(frame)的形式传递
                             * 可以看到WebSocketFrame下面有6个子类
                             * 浏览器发送请求时候 ws://localhost:7000/xxx
                             * WebSocketServerProtocolHandler用于请求的对应路径，比如上面/xxx或者/aaa
                             * 它还有一个核心功能，也就是将http协议升级为ws，也就是长连接websocket（保持长连接）
                             * 主要是通过修改状态码为101来升级协议为ws协议
                             * */
                             pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
                             //自定义处理器，处理业务逻辑,经过上面的WebSocketServerProtocolHandler处理之后就会进入这个处理器
                            pipeline.addLast(new MyTextWevSocketFrameHandler());
                        }
                    });
            //启动服务器
            ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
            //关闭监测，阻塞主线程等待子线程运行
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
